package com.xiaochun.hxhj;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.fragment.app.FragmentManager;

import com.util.CommentDialog;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.StatusBarUtil;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;

public class VipActivity extends BaseActivity {
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.tv_content_one)
    TextView tv_content_one;
    @BindView(R.id.tv_content_two)
    TextView tv_content_two;
    @BindView(R.id.tv_viptime)
    TextView tv_viptime;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.tv_buy_vip)
    TextView tv_buy_vip;
    @BindView(R.id.ll_rebackq)
    LinearLayout ll_rebackq;
    private String token;
    private String title_desc;
    private String vip_title_desc;
    private String vip_expire;
    private String vip_desc;
    private PopupWindow mPopupWindow;
    private String bindtitle;
    private String bindtitle_desc;
    private String is_vip;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initListener() {
        tv_buy_vip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                popbyexit();

                    FragmentManager manager = getSupportFragmentManager();//区分是v4的Fragment还是app包里面的
                    CommentDialog dialogFragment = new CommentDialog();
                    dialogFragment.show(manager, "custom");

            }
        });
        ll_rebackq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }



    @Override
    protected int initLayout() {
        return R.layout.activity_vip;
    }

    @Override
    protected void initView() {

        StatusBarUtil.transparencyBar(this); //设置状态栏全透明
//        StatusBarUtil.StatusBarLightMode(this); //设置白底黑字
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        token = getUserInfo("token");
        is_vip = getUserInfo("is_vip");
        if ("1".equals(is_vip)) {
            //是会员
            tv_buy_vip.setText("立即续费");
        }else if ("0".equals(is_vip)){
            //不是会员
            tv_buy_vip.setText("立即开通");
        }

        webview.setBackgroundColor(0);//设置背景色
//        webview.getBackground().setAlpha(0);//设置填充透明度（布局中一定要设置background，不然getbackground会是null）

        getData();

    }


    @Override
    protected void initData() {

    }

    private void getData() {
        token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/vip/vipdesc";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        MyLog.e("获取用户信息",url+"   token="+token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");

                    title_desc = data.getString("title_desc");
                    vip_title_desc = data.getString("vip_title_desc");
                    vip_expire = data.getString("vip_expire");
                    vip_desc = data.getString("vip_desc");



                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private void bindVip(String no) {
        token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/vip/bind";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("card_no", no);
        MyLog.e("绑定会员卡",url+"   token="+token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }


                    JSONObject data = jsonObject.getJSONObject("data");
                    bindtitle = data.getString("title");
                    bindtitle_desc = data.getString("title_desc");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);

                    break;
                case 1:

                    break;
                case 2:

                    break;
                case 3:
//                    String obj = (String) msg.obj;
//                    ToastUtils.show(obj);
                    mPopupWindow.dismiss();
                    bindsuccess();


                    break;
                case 4:
                    String username = getUserInfo("username");
                    String nickname = getUserInfo("nickname");
                    tv_username.setText("Hi,"+nickname);
                    tv_content_one.setText(title_desc);
                    tv_content_two.setText(vip_title_desc);
                    tv_viptime.setText(vip_expire);
                    webview.getSettings().setDefaultTextEncodingName("UTF-8");
                    webview.loadDataWithBaseURL(null, vip_desc+"<style> img{max-width:100%;max-height:100%} </style>", "text/html", "utf-8", null);
                    webview.setWebViewClient(new WebViewClient());

                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();



                    break;
                case 12:

                    break;
            }
        }
    };

    /**
     * 弹出退出页面搜索框
     */
    private void popbyexit() {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_buy_course, null);

        ImageView img_colse = popupWindow.findViewById(R.id.img_colse);
        EditText et_xlh = popupWindow.findViewById(R.id.et_xlh);
        TextView tv_buy = popupWindow.findViewById(R.id.tv_buy);

        img_colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });
        tv_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
                String trim = et_xlh.getText().toString().trim();
                if ("".equals(trim)){
                    ToastUtils.show("请输入会员序列号");
                }else{
                    bindVip(trim);
                }

            }
        });

        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindow.showAtLocation(tv_buy_vip,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindow.showAtLocation(tv_buy_vip,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }
    /**
     * 弹出退出页面搜索框
     */
    private void bindsuccess() {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_buy_course, null);

        ImageView img_colse = popupWindow.findViewById(R.id.img_colse);
        EditText et_xlh = popupWindow.findViewById(R.id.et_xlh);
        TextView tv_buy = popupWindow.findViewById(R.id.tv_buy);
        TextView tv_bind_time = popupWindow.findViewById(R.id.tv_bind_time);
        TextView tv_content_status = popupWindow.findViewById(R.id.tv_content_status);
        et_xlh.setVisibility(View.GONE);
        tv_bind_time.setVisibility(View.VISIBLE);
        tv_content_status.setText(bindtitle);
        tv_bind_time.setText(bindtitle_desc);
        tv_buy.setText("确定");
        img_colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });
        tv_buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });
        et_xlh.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                MyLog.e("长按事件","长按事件");

                return true;
            }
        });


            mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindow.showAtLocation(tv_buy_vip,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindow.showAtLocation(tv_buy_vip,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,VipActivity.this,tv_buy_vip);
//            popbyexit(type);
        }
    }


}
